package vn.mobisoft.gachno;

import java.io.IOException;
import java.util.Calendar;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Report_dot extends Activity implements NetworkInterface{
	
	private ListView list;
	private MyCustomAdapter mAdapter;
	private Vector<Report_item> mData = new Vector<Report_item>();
	
	private Button btn_exit;
	String rawdata = "";
	String total = "";
	
	private int year;
	private int month;
	private int day;
	
	private int page = 1;
	private int step = 10;
	private String lan_giao = "";
	
	private int totalRecord=-1;
	private int totalMoney=-1;
	
	static final int DATE_DIALOG_ID = 999;
	
	private TextView 	text_total;
	private TextView 	text_date;

	//private DatePicker dpResult;
	
	private static final int 	DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog 		mProgressDialog;
	
	private Function function = new Function();
	private int action;
	protected int selectedItem;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.report_dot);
        
        
        text_date = (TextView)findViewById(R.id.rd_textView_date);
        //text_date.setText(Function.getDateMonthYear1());
		// set current date into textview
        //text_date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" "));
        
		Bundle extras = getIntent().getExtras();
		if (extras != null) {			
			rawdata = extras.getString("REPORT_INFOR");
			String[] a = rawdata.split(":");
			lan_giao = a[1];
			text_date.setText(a[2].substring(0, a[2].length()-3));
		//	parseInfor(rawdata);
		}
        
        mAdapter = new MyCustomAdapter(this);  
        list = (ListView)findViewById(R.id.rd_listView);
        list.setAdapter(mAdapter);      
        
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int pos,
					long arg3) 
			{
				selectedItem = pos;
				final CharSequence[] items = {	"Tên khách hàng: " + mData.elementAt(pos).ten_khachhang, 
												"Mã hóa đơn: " + mData.elementAt(pos).ma_tt, 
												"Số đt: " + mData.elementAt(pos).sodt,
												"Số nợ: " + toCurent(mData.elementAt(pos).so_tien) +" vnđ"}; 

				AlertDialog.Builder builder = new AlertDialog.Builder(arg1.getContext());
				builder.setTitle("Thông tin khách hàng");
				builder.setItems(items, null);
				
				builder.setPositiveButton("Thoát", new  android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				});
				
				builder.setNegativeButton ("Hủy gạch nợ", new  android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (mData.elementAt(selectedItem).ngay_hien_tai.equals(mData.elementAt(selectedItem).ngay_thanh_toan)) {
							onConnect(CONSTANT.ACTION_HUY_GACH_NO);	
						}else {
							Toast.makeText(getApplicationContext(), "Chỉ hủy được phiếu trong ngày!", Toast.LENGTH_LONG).show();
						}															
					}
				});
				
				AlertDialog alert = builder.create();
				alert.show();

			}
		});
       //mData.add("");
        
        btn_exit = (Button)findViewById(R.id.rd_button_exit);
        btn_exit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
        
        text_total = (TextView)findViewById(R.id.rd_textView_total);
        text_total.setText(total);


		///final Calendar c = Calendar.getInstance();
		//year = c.get(Calendar.YEAR);
		//month = c.get(Calendar.MONTH);
		//day = c.get(Calendar.DAY_OF_MONTH);
        
        onConnect(CONSTANT.ACTION_REPORT_DOT);
    }
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month, day);			
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setTitle("");
			mProgressDialog.setMessage("Xin chờ trong giây lát!");
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			//text_date.setText(new StringBuilder().append(month + 1).append("-").append(day).append("-").append(year).append(" "));
			text_date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" "));
			
			// set selected date into datepicker also
			//dpResult.init(year, month, day, null);

			//Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
			
			//lgThread = new LoginAsync();
			//lgThread.execute();
		}

	};
	
    private class MyCustomAdapter extends BaseAdapter {
        private LayoutInflater 		mInflater;
        private Context activity;
        
        public MyCustomAdapter(Context a) {
        	activity = a;
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        public int getCount() {
            return mData.size();
        }
 
        public Report_item getItem(int position) {
            return mData.get(position);
        }
 
        public long getItemId(int position) {
            return position;
        }
 
		@Override
		public View getView(final int pos, View convertView, ViewGroup parent) {       	
    		convertView = mInflater.inflate(R.layout.report_item, null);  
    		
    		TextView name = (TextView)convertView.findViewById(R.id.ri_textView_name);
    		name.setText((pos+1)+": "+mData.elementAt(pos).ten_khachhang);
    		
    		TextView address = (TextView)convertView.findViewById(R.id.ri_textView_infor);
    		address.setText(mData.elementAt(pos).sodt);
    		
    		TextView money = (TextView)convertView.findViewById(R.id.ri_textView_money);
    		money.setText(toCurent(mData.elementAt(pos).so_tien));
    		
            return convertView;
		}
    }
    public String toCurent(String s) {
		int m= Integer.parseInt(s);
		return String.format("%,d",m);
    }
    
    public void onConnect(int connectType, String... arg) {
    	action = connectType;
    	String link = "";
    	switch (connectType) {
    	
		case CONSTANT.ACTION_REPORT_DOT:
			link = String.format(CONSTANT.LINK_REPORT_DOT, ((Global)getApplication()).getMid(),lan_giao,  page+"", step+"");
			break;	
		} 
    	   	
    	Network network = new Network();
    	network.onConnectListener(this);
    	network.execute(link);
    }
    
    
	@Override
	public void startNetworkConnect() {
		showDialog(DIALOG_DOWNLOAD_PROGRESS);		
	}

	@Override
	public void networkProgressUpdate(String... progress) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stopNetworkConnect(String result) {
		System.out.println(result);
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		if (result==null) {
			return;
		}
		
		result = result.trim();
		switch (action) {
		case CONSTANT.ACTION_REPORT_DOT:	
			if (page==1) {
				String s[] = result.split("<br/>");
				if (s.length>1) { 
					try {
						totalRecord = Integer.parseInt(s[0]);
						totalMoney  = Integer.parseInt(s[1].substring(s[1].indexOf(":")+1));
					} catch (NumberFormatException e) {
						totalRecord = 0;
						totalMoney = 0;
						e.printStackTrace();
					}
					text_total.setText(totalRecord +" phiếu  "+toCurent(totalMoney+"")+" vnđ");
				} 				
			}
			
			mData = function.parseReportList(result);
			mAdapter.notifyDataSetChanged();
			break;
		}
	}

	private void updateList() {
		//mData.clear();
		onConnect(CONSTANT.ACTION_REPORT);
		//mData.removeElementAt(selectedItem);
		//mAdapter.notifyDataSetChanged();
	}

	@Override
	public void networkError(IOException e) {
		// TODO Auto-generated method stub
		
	}	

}
